package com.gao.xml.jaxb;

import com.gao.xml.jaxb.util.XMLUtil;
import com.gao.xml.jaxb.xml.ClassInfo;
import com.gao.xml.jaxb.xml.Student;
import com.gao.xml.jaxb.xml.Teacher;
import com.gao.xml.jaxb.xml.User;
import lombok.SneakyThrows;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author GaoXi
 * @date 2021/8/18 10:33
 */
public class Demo {

    String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
        "<Class> \n" +
        "  <id>1</id>  \n" +
        "  <name>CS科班</name>  \n" +
        "  <stuInfo size=\"3\"> \n" +
        "    <stu> \n" +
        "      <id>0001</id>  \n" +
        "      <name>李四</name> \n" +
        "    </stu>  \n" +
        "    <stu> \n" +
        "      <id>0002</id>  \n" +
        "      <name>张已</name> \n" +
        "    </stu>  \n" +
        "    <stu> \n" +
        "      <id>0003</id>  \n" +
        "      <name>王强</name> \n" +
        "    </stu> \n" +
        "  </stuInfo> \n" +
        "</Class>";

    String userXml = "<user xmlns:ns2=\"http://www.baidu.com/schema\">\n" +
        "    <ns2:value>111</ns2:value>\n" +
        "    <name>gaoxi</name>\n" +
        "</user>";

    /**
     * 解析测试
     */
    @Test
    public void testXmlParse(){
        User o =(User) XMLUtil.convertXmlStrToObject(User.class, userXml);
        System.out.println(o);
    }


    /**
     * 生成测试
     */
    @Test
    public void testXmlAccessType(){
        User user = new User();
        System.out.println(XMLUtil.convertToXml(user));
    }


    /**
     * 生成测试
     */
    @Test
    public void testGen(){
        ClassInfo classInfo = new ClassInfo();
        classInfo.setId("1");
        classInfo.setName("CS科班");
       /* Teacher teacher = new Teacher();
        teacher.setId("2");
        teacher.setName("高老师");
        classInfo.setTeacher(teacher);*/
        List<Student> students = Arrays.asList(new Student("2", "高溪"),
            new Student("3", "高吸"));
        classInfo.setStu(students);
        System.out.println(XMLUtil.convertToXml(classInfo));
    }


    /**
     * 解析
     */
    @Test
    public void testJaxb(){
        ClassInfo classInfo = (ClassInfo) XMLUtil.convertXmlStrToObject(ClassInfo.class, xmlStr);
        System.out.println(classInfo);
    }


    /**
     * 原生代码
     */
    @SneakyThrows
    @Test
    public void testJaxbFile(){
        ClassPathResource classPathResource = new ClassPathResource("test.xml");
        File file = classPathResource.getFile();

        //=====一下是重点========
        JAXBContext jaxbContext = JAXBContext.newInstance(ClassInfo.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Object unmarshal = unmarshaller.unmarshal(file);
        System.out.println((ClassInfo) unmarshal);
    }












}
